<?php

namespace app\backstage\controller;

use app\backstage\service\UserService;

class User extends Base
{
	protected $datas;
	protected $title;
	
	public function index()
	{
		$this->datas = $this->params;
		$this->title = '用户列表';
		if (isset($this->datas['username'])) {
			//搜索
			$username = $this->datas['username'];
			$nickname = $this->datas['nickname'];
			$mobile = $this->datas['mobile'];
			$whereMap = [];
			if (!empty($username)) {
				$whereMap[] = ['username', 'like', '%'. $username .'%'];
			}
			if (!empty($nickname)) {
				$whereMap[] = ['nickname', 'like', '%'. $nickname .'%'];
			}
			if (!empty($mobile)) {
				$whereMap[] = ['mobile', '=', $mobile];
			}
			$list = UserService::pageList($whereMap, 'id desc');
		}else {
			$list = UserService::pageList([], 'id desc');
		}
		$this->assign([
			'title' => $this->title,
			'list' => $list
		]);
		return $this->fetch();
	}

	public function form()
	{
		if (request()->isPost()) {
			$this->datas = $this->params;
			if ($this->datas['password'] != $this->datas['repassword']) {
				$this->error('请确保二次密码一致');
			}
			$data = [
				'username' => $this->datas['username'],
				'password' => md5($this->datas['password']),
				'gender' => $this->datas['gender'],
				'birthday' => strtotime($this->datas['birthday']),
				'register_time' => time(),
				'nickname' => $this->datas['nickname'],
				'mobile' => $this->datas['mobile'],
				'register_ip' => request()->ip(),
				'avatar' => $this->datas['avatar']
			];
			if (isset($this->datas['id'])) {
				$result = UserService::update('id', $this->datas['id'], $data);
			} else {
				$result = UserService::add($data);
			}
			if (!$result) {
				$this->error('失败');
			}
			$this->success('成功');
		}
		$id = input('id', '', 'trim');
		$data = [];
		if (!empty($id)) {
			$data = UserService::getInfo('id', $id);
		}
		$this->assign(['data' => $data]);
		return $this->fetch();
	}


	public function uploadimg()
	{
		$path = 'static'. DS . 'upload' . DS . 'avatar';
		$size = 58400*100;
		$type = 'jpg,png,gif,jpeg';
		$uploadResult = uploadFile('file', $path, $size, $type);
		if (!$uploadResult[0]) {
			$this->error($uploadResult[1]);
		}
		$this->success('上传成功', '', $uploadResult[1]);
	}
}